import json
import requests
import hashlib
import time
from urllib.parse import quote
# import logging

# 配置日志
# logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 定义一个包含多个oid的列表
oid_list = ['818815049']

def GetResponse(url,data):
    # 模拟浏览器
    headers={
    "user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36",
    "cookie":"buvid3=460622C0-20B7-A1E3-EBC3-A4619CD92B7B60171infoc; b_nut=1695200260; i-wanna-go-back=-1; b_ut=7; _uuid=DD8103325-E444-818C-851C-21C7A13E85DA60108infoc; buvid4=451E789B-6BD2-97D3-A42C-7C7271F4D96861250-023092016-e63QcPwqs3fsueWE19Mwcg%3D%3D; rpdid=|(um~lum~)Ym0J'uYmlk~l)u|; buvid_fp_plain=undefined; enable_web_push=DISABLE; header_theme_version=CLOSE; hit-dyn-v2=1; FEED_LIVE_VERSION=V8; DedeUserID=1202949524; DedeUserID__ckMd5=ebca5a3a999edb01; LIVE_BUVID=AUTO4817225840721883; PVID=3; CURRENT_FNVAL=4048; home_feed_column=4; CURRENT_QUALITY=80; fingerprint=8ca92853f7b5b577b4041374ed8aead2; buvid_fp=8ca92853f7b5b577b4041374ed8aead2; SESSDATA=090716c1%2C1739104886%2Cb5c2f%2A81CjAucm2iKWv5ItqDacPEhJnq9gHkE0Sp8uTmuqoAsoNHuAnGLcmB1_AyaoIY0jHmjaMSVlJwX1FuZzRneEdCQkpOVGlpUUFmSVVTR3RIVDhZckZIeDRWQWt5M3c0Z2ZpZGtJWHJOb0NRTlNxc2NiMHFnV2F4RF9XR1RRYkx2ZF9aQUh0aUxFSEZBIIEC; bili_jct=40b6ff108668faaf2599ef0a6f8f866a; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MjM4MTc0MjYsImlhdCI6MTcyMzU1ODE2NiwicGx0IjotMX0.1wgeKYlFRu0mM5xZwrDmbdCrbrqNdNh_xuGA9t6XGRQ; bili_ticket_expires=1723817366; sid=6lh8t15c; bp_t_offset_1202949524=965699078400770048; bsource=search_baidu; b_lsid=31098634F_1915503FF72; browser_resolution=560-520",
    }
    # 发送请求
    response = requests.get(url=url, params=data, headers=headers)
    return response

def GetContent(oid, date, NextPage, w_rid,max_length=120,min_length=10):
    print('获取数据参数:', NextPage)
    link = 'https://api.bilibili.com/x/v2/reply/wbi/main'
    # 查询参数
    params = {
        'oid': oid,
        'type': '1',
        'mode': '3',
        'pagination_str': '{"offset": %s}' % NextPage,
        'plat': '1',
        'web_location': '1315875',
        'w_rid': w_rid,
        'wts': date
    }
    # 发送请求函数
    response = GetResponse(url=link, data=params)
    # 获取响应内容
    json_data = response.json()
    print(json_data)
    # 解析数据
    content_list = [i['content']['message'] for i in json_data['data']['replies']]
    # # for循环遍历，输出每个元素
    for content in content_list:
        content = content.replace('\n',' ')
        content_length = len(content)
        # 检查评论长度是否在允许范围内
        if not (min_length <= content_length <= max_length):
            print(
                f"忽略评论（长度：{content_length}）：{content[:max_length if content_length > max_length else min_length]}...")
            continue  # 跳过此循环迭代
        print(content)
        f.write(content + '\n')

    # print(content_list)
    # 获取下一页的参数内容
    next_offset = json.dumps(json_data['data']['cursor']['pagination_reply']['next_offset'])
    # offset = json.dumps(next_offset)
    return next_offset

def Hash(date, NextPage, oid):
    next_offset = '{"offset": %s}' % NextPage
    # .replace('%3A', ':')
    pagination_str = quote(next_offset)
    print('加密next_offset:',next_offset)
    print('加密pagination_str:',pagination_str)
    l = [
        "mode=3",
        f"oid={oid}",
        f"pagination_str={pagination_str}",
        "plat=1",
        # "seek_rpid=",
        "type=1",
        "web_location=1315875",
        f"wts={date}"
    ]
    y = '&'.join(l)
    string = y + "ea1db124af3c7062474693fa704f4ff8"
    MD5 = hashlib.md5()
    MD5.update(string.encode('utf-8'))
    w_rid = MD5.hexdigest()
    print(w_rid)
    return w_rid


if __name__ == '__main__':
    f = open('bili_remark_data.csv', mode='a', encoding='utf-8', newline='')
    # 遍历oid列表
    for oid in oid_list:
        # 定义第一页参数
        NextPage = '""'

        for page in range(1,30):
            print(f'正在采集视频{oid}的第{page}页内容')
            date = int(time.time())
            time.sleep(4)
            # date = 1723723571
            # 获取当前时间戳
            w_rid = Hash(date=date, NextPage=NextPage,oid=oid)
            # 获取数据内容
            NextPage = GetContent(oid, date, NextPage, w_rid)
            print(NextPage)
    f.close()  # 关闭文件